#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/21 0021 12:49
# @Author  : Arliki
# @File    : tcp_server.py
import socket
import threading
import time


def run():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('127.0.0.1', 9999))
    s.listen(3)
    print('等待链接... ...')
    while 1:
        sock, addr = s.accept()
        t = threading.Thread(target=tcplink, args=(sock, addr))
        t.start()


def tcplink(sock, addr):
    print('成功链接来自 .%s:%s. 发送信息' % addr)
    sock.send(b'welcome')
    while 1:
        data = sock.recv(1024)
        time.sleep(2)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(('欢迎你%s' % data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print("已经关闭来自%s:%s的链接" % addr)


def run_udp():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(('127.0.0.1', 9999))
    print("waiting for udp")
    while 1:
        data, addr = s.recvfrom(1024)
        print('receive from %s' % str(addr))
        s.sendto(b'welcome %s' % data.decode('utf-8').encode('utf-8'), addr)


if __name__ == '__main__':
    run_udp()
